package com.example.tongyao.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.tongyao.system.entity.SysMenu;
import com.example.tongyao.system.entity.SysUser;
import com.example.tongyao.system.service.ISysMenuService;
import com.example.tongyao.system.service.ISysRoleMenuService;
import com.example.tongyao.utils.DataResult;
import com.example.tongyao.utils.tools.PubClass;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author tongyao
 * @since 2020-06-13
 */
@RestController
@Api(tags = "系统 - 菜单管理")
@RequestMapping("/system/sys-menu")
public class SysMenuController {

    @Autowired
    private ISysMenuService iSysMenuService;

    @Autowired
    private ISysRoleMenuService iSysRoleMenuService;


    @ApiOperation(
            value = "1、增加菜单信息",
            notes = "增加菜单信息",
            httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysMenu",value = "菜单信息",required = true),
    })
    @RequiresPermissions("menu")
    @PostMapping(value = "/add" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult add(@RequestBody(required = true) SysMenu sysMenu) {
        //获取登录的用户信息
        SysUser sessionUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        sysMenu.setCreateBy(sessionUser.getUserName());
        sysMenu.setCreateTime(PubClass.getDateTime());
        boolean isResult = iSysMenuService.save(sysMenu);
        if(!isResult){
            return DataResult.setError("用户菜单失败！");
        }
        return DataResult.setSuccess("添加菜单成功！");
    }

    @ApiOperation(
            value = "2、批量和单个删除菜单信息",
            notes = "批量和单个删除用户信息",
            httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "删除的id数组，以小写逗号隔开，不传逗号，则是单个删除，会把父级地下的所有子项全部删除。",required = true),
    })
    @RequiresPermissions("menu")
    @DeleteMapping(value = "/delete" , produces = {MediaType.APPLICATION_JSON_VALUE})// 请求
    public DataResult delete(@RequestParam(required = true) String ids) {
        if(StringUtils.isEmpty(ids)){
            return DataResult.setError("用户ids为空！");
        }
        //判断是批量删还是单个删
        if(ids.indexOf(",")!=-1){
            String[] id = ids.split(",");
            List<String> idS = new ArrayList<>(Arrays.asList(id));
            iSysMenuService.removeByIds(idS);

            Map<String,Object> map = new HashMap<>();
            for(String str : idS){
                map.put("menu_id",str);
                iSysRoleMenuService.removeByMap(map);
            }
        }else{
            List<String> idS = getParentChildId(iSysMenuService.list(),ids);
            iSysMenuService.removeByIds(idS);

            Map<String,Object> map = new HashMap<>();
            for(String str : idS){
                map.put("menu_id",str);
                iSysRoleMenuService.removeByMap(map);
            }
        }

        return DataResult.setSuccess("删除成功！");
    }

    /**
     * 递归获取子父级id
     * @param sysMenuList
     * @param parentId
     * @return
     */
    public List<String> getParentChildId(List<SysMenu> sysMenuList,String parentId){
        List<String> list = new ArrayList<>();
        list.add(parentId);
        List<String> sons = new ArrayList<String>();
        sons.add(parentId);
        List<String> temp=new ArrayList<String>();
        while(true){
            for(String str:sons){
                for(SysMenu sysMenu : sysMenuList) {
                    if(str.equals(sysMenu.getParentId()+"")){
                        temp.add(sysMenu.getId()+"");
                        list.add(sysMenu.getId()+"");
                        //System.out.println("删除了ID=["+treeMenu.getId()+"]的节点,其父节点为["+str+"]");
                    }
                }
            }
            if(temp.size()>0){
                sons=temp;
                temp=new CopyOnWriteArrayList<String>();
            }else{
                break;
            }
        }
        return list;
    }

    @ApiOperation(
            value = "3、修改菜单信息",
            notes = "修改菜单信息",
            httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysMenu",value = "要修改的菜单总体信息",required = true),
    })
    @RequiresPermissions("menu")
    @PutMapping(value = "/update")// 请求
    public DataResult update(@RequestBody(required = true) SysMenu sysMenu) {
        //获取登录的用户信息
        SysUser sessionUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        sysMenu.setModifyBy(sessionUser.getUserName());
        sysMenu.setModifyTime(PubClass.getDateTime());
        boolean isResult = iSysMenuService.updateById(sysMenu);
        if (!isResult){
            return DataResult.setError("菜单信息更改失败！");
        }
        return DataResult.setSuccess("修改成功！");
    }

    @ApiOperation(
            value = "4、更新菜单状态",
            notes = "通过传过来的菜单id，修改菜单的状态",
            httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menuId",value = "用户id",required = true),
            @ApiImplicitParam(name = "status",value = "状态true或false",required = true)
    })
    @RequiresPermissions("menu")
    @PutMapping(value = "/updateStatus")// 请求
    public DataResult updateStatus(@RequestParam(required = true) String menuId,
                                   @RequestParam(required = true,defaultValue = "true") boolean status ) {
        if(StringUtils.isEmpty(menuId)){
            return DataResult.setError("菜单Id为空！");
        }
        LambdaUpdateWrapper<SysMenu> sysUserLambdaUpdateWrapper =new LambdaUpdateWrapper<>();
        sysUserLambdaUpdateWrapper.set(SysMenu::getMenuStatus,status).eq(SysMenu::getId,menuId);
        boolean isResult = iSysMenuService.update(sysUserLambdaUpdateWrapper);
        if (!isResult){
            return DataResult.setError("状态更改失败！");
        }
        return DataResult.setSuccess("状态更改成功！");
    }

    /**
     * 分页查询所有用户
     * @return
     */
    @ApiOperation(
            value = "5、查询所有菜单",
            notes = "查询所有菜单",
            httpMethod = "GET")
    @RequiresPermissions("menu")
    @GetMapping(value = "/page" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult page() {
        LambdaQueryWrapper<SysMenu> sysMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();

        List<SysMenu> sysMenuList = iSysMenuService.list(sysMenuLambdaQueryWrapper);
        return DataResult.setSuccess(sysMenuList);
    }

}
